package cn.com.callback

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.PropertiesUtil;
import cn.com.elite.Util;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
/**
 * 
 * @author msjykf
 * 根据入参guid返回一个查看邮件正文的url
 * {"guid":"","type":1}
 *
 */
public class ReadEmailContent implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(ReadEmailContent.class);
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request,HttpServletResponse response){
		try {
			def jsonbody = Util.getRequestBody(request,'utf-8'); //获取报文
			if(jsonbody.equals("")) {
				return "{\"msg\": \"未获取到入参报文！\",\"code\": -2}"
			};
			JSONObject obj = JSONObject.fromObject(jsonbody);
			def rec_guid = Util.filterForObject(obj.get("guid"));
			int type = obj.get("type");
			def content,map;
			if(rec_guid.equals("")){
				return "{\"msg\": \"guid参数不能为空！\",\"code\": -2}"
			};
			if(type =='1') {
				map = eliteBean.chaxun_sql("select content from email_send_task where rec_guid='"+rec_guid+"'","dataSource");
			}else if (type =='2') {
				map = eliteBean.chaxun_sql("select content from documentout where documentout_guid='"+rec_guid+"'","dataSource");
			}else if (type =='3') {
				map = eliteBean.chaxun_sql("select content from documentout_his where documentout_guid='"+rec_guid+"'","dataSource");
			};
			if(map.size()==0) {
				return "{\"msg\": \"guid参数无效！\",\"code\": -2}"
			}else {
				content = Util.filterForObject(map[0].get("content"));
			};
			PropertiesUtil properties = new PropertiesUtil();
			def ccserverip = properties.readValue("ccserverip"); //获取CallCenter访问地址
			def fileStore = properties.readValue("fileStore"); //文件存储根目录
			def filepath = "emailtemplate/ReadEmailContent.html" //文件存储相当路径
			File file = new File(fileStore+"/"+filepath); //文件存储绝对路径
			//文件不存在，则创建文件
			if(!file.exists()) {
				file.createNewFile();
			};
			
			FileOutputStream fs = new FileOutputStream (file,false);
			OutputStreamWriter os= new OutputStreamWriter (fs,"UTF-8")
			BufferedWriter bw = new BufferedWriter (os);
			
			//FileWriter fw = new FileWriter(file,false);
			//BufferedWriter bw=new BufferedWriter(fw);
			bw.write(content.replace("charset=gb2312", "charset=utf-8"));
			bw.flush();
			bw.close();
			os.close();
			fs.close();
			//fw.close();
			def httpurl = "http://"+ccserverip+"/ngs/fs/get?file="+filepath;
			return "{\"msg\": \"请求接口成功！\",\"code\": 1,\"httpurl\": \""+httpurl+"\"}"
		}catch(Exception e) {
			log.error("ErrorMessage： ",e);
			return "{\"msg\": \"请求接口失败！\",\"code\": -1}"
		}
	}
}